package com.renhuikeji.pro.ala.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ali.auth.third.core.model.Session;
import com.alibaba.baichuan.android.trade.adapter.login.AlibcLogin;
import com.alibaba.baichuan.android.trade.callback.AlibcLoginCallback;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.renhuikeji.pro.ala.R;
import com.renhuikeji.pro.ala.bean.BasicBean;
import com.renhuikeji.pro.ala.bean.LoginCodeBean;
import com.renhuikeji.pro.ala.bean.MemberInfoBean;
import com.renhuikeji.pro.ala.bean.MsgBean;
import com.renhuikeji.pro.ala.config.Constant;
import com.renhuikeji.pro.ala.utils.DealResUtil;
import com.renhuikeji.pro.ala.utils.KeyBoardUtils;
import com.renhuikeji.pro.ala.utils.LogUtil;
import com.renhuikeji.pro.ala.utils.OkHttpUtils;
import com.renhuikeji.pro.ala.utils.SPUtils;
import com.renhuikeji.pro.ala.utils.StringUtil;
import com.renhuikeji.pro.ala.utils.ToastUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_phone_login)
    EditText et_phone_login;
    @BindView(R.id.et_password_login)
    EditText et_password_login;
    @BindView(R.id.iv_show_pd)
    ImageView iv_show_pd;
    @BindView(R.id.btn_login)
    TextView btn_login;

    public boolean showPd = false;
    @BindView(R.id.tv_to_register_login)
    TextView tv_to_register_login;
    @BindView(R.id.img_login_back)
    ImageView imgLoginBack;
    @BindView(R.id.tv_forget_psw)
    TextView tv_forgetpsw;
    private String session;
    private String old_session;
    private String uid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        old_session = (String) SPUtils.get(LoginActivity.this, Constant.MSESSION, "");
        uid = (String) SPUtils.get(this, Constant.User_Uid, "");

    }

    private void booleanLogin() {
        String phoneLogin = et_phone_login.getText().toString().trim();
        if (TextUtils.isEmpty(phoneLogin)) {
            showToast("请输入正确的用户名");
            return;
        }

        String passwordLogin = et_password_login.getText().toString().trim();
        if (StringUtil.isEmpty(passwordLogin)) {
            showToast("请输入密码");
            return;
        }
        if (!StringUtil.passwordCheck(passwordLogin)) {
            showToast("密码格式不对");
            return;
        }

        //关闭软键盘
        KeyBoardUtils.closeKeybord(et_password_login, LoginActivity.this);
        login(phoneLogin, passwordLogin);
    }

    private void login(final String name, final String psw) {

        OkGo.<String>post(Constant.BASE_URL+"?g=api&m=member&a=login")
                .params("mobile",name)
                .params("pwd",psw)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        MsgBean bean= DealResUtil.getInstace().dealRes(LoginActivity.this,response,new TypeToken<BasicBean<MsgBean>>(){}.getType());
                        if(bean!=null){
                                SPUtils.put(LoginActivity.this, Constant.User_Uid, bean.getMid());
                                SPUtils.put(LoginActivity.this, Constant.User_Phone, name);
                                SPUtils.put(LoginActivity.this, Constant.User_Psw, psw);
                                Intent i = new Intent(LoginActivity.this, MainActivity.class);
                                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(i);
                        }

                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(LoginActivity.this,getString(R.string.bad_net));
                    }
                });
    }

    //    显示或隐藏密码
    private void isShowPd() {

        if (showPd) {
            et_password_login.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            showPd = false;
        } else {
            et_password_login.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            showPd = true;
        }
    }

    @OnClick({R.id.img_login_back, R.id.iv_show_pd, R.id.btn_login, R.id.tv_to_register_login, R.id.tv_forget_psw})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_login_back:
                LoginActivity.this.finish();
                break;
            case R.id.iv_show_pd:
                isShowPd();
                break;
            case R.id.btn_login:
//                login();
                booleanLogin();
                break;
            case R.id.tv_to_register_login:  //注册
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_forget_psw:  //忘记密码
                Intent intent1 = new Intent(LoginActivity.this, ResetPassWordActivity.class);
                startActivity(intent1);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        getApp().finishAllActivity();
    }


    public void login( ) {
        final AlibcLogin alibcLogin = AlibcLogin.getInstance();
        alibcLogin.showLogin(LoginActivity.this, new AlibcLoginCallback() {
            @Override
            public void onSuccess() {
                Toast.makeText(LoginActivity.this, "登录成功 ",
                        Toast.LENGTH_LONG).show();
                //获取淘宝用户信息
                Session ss = AlibcLogin.getInstance().getSession();
                Log.i("CCC", "获取淘宝用户信息: "+AlibcLogin.getInstance().getSession());
                Intent i = new Intent(LoginActivity.this, MainActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
//                nick = q562251447, ava = https://wwc.alicdn.com/avatar/getAvatar.do?userId=728861855&width=160&height=160&type=sns
//            , openId=AAFD1OGbAFistRbUqJtvcPff, openSid=5e6214c7cc7e4e9101436361fb9ec28d650af4e484077af8189232de04adf138264e3549c0ee7b319f6f983604416497
                saveUserInfo(ss);
            }
            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(LoginActivity.this, "登录失败 ", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void saveUserInfo(Session session) {
        String url="http://alayifan.liexianghudong.com/index.php?g=api&m=index&a=saveInfo";
        OkGo.<String>post(url)
                .params("openid", session.openId)
                .params("avatar", session.avatarUrl)
                .params("nickname", session.nick)
                .params("from_type", 1)
                .params("phone_type", 1)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }
}
